<template>
	<div>
		<div style="margin: 20px 0;">
			<el-input style="width: 200px;" placeholder="输入追溯码" v-model="code_" clearable maxlength="50" />
			<el-button type="primary" style="margin-left: 20px;" @click="getPallet">
				查询
			</el-button>
		</div>
		<list-page :data="listPageConfig">
			<!-- <audio src="./baojing.mp3" ref="audio"></audio> -->
			<audio ref="audio">
				<source src="../baojing.mp3" type="audio/mp3">
			</audio>
			<audio ref="audio1">
				<source src="../chenggong.mp3" type="audio/mp3">
			</audio>

			<template v-slot:tableColumn>

				<el-table-column align="center" label="工单号" type="index" width="250">
					<template v-slot="{row}">{{row.corpOrderID}}</template>
				</el-table-column>
				<el-table-column align="center" label="托盘码" type="index" width="250">
					<template v-slot="{row}">{{row.code}}</template>
				</el-table-column>
				<!-- 			<el-table-column align="center" label="托盘码">
		 				<template v-slot="{row}">{{row.pallet_code}}</template>
		 			</el-table-column>
		 			<el-table-column align="center" label="箱码">
		 				<template v-slot="{row}">{{row.case_code}}</template>
		 			</el-table-column> -->
				<el-table-column align="center" label="托盘状态">
					<template v-slot="{row}">
						<span v-if="row.process == 1">正在入库</span>
						<span v-if="row.process == 2">完成入库</span>
						<span v-if="row.process == 3">正在出库</span>
						<span v-if="row.process == 4">完成出库</span>
					</template>
				</el-table-column>
				<el-table-column align="center" label="绑定时间" type="index" width="150">
					<template v-slot="{row}">{{row.actDate?formatDate(row.actDate,'yyyy-MM-dd hh:mm'):''}}</template>
				</el-table-column>
				<!-- 			<el-table-column al
		 	<!-- 		<el-table-column align="center" label="箱码状态">
		 				<template v-slot="{row}">
		 					<span v-if="row.case_code_status == 1">已绑定</span>
		 					<span v-if="row.case_code_status == 2">已解绑</span>
		 				</template>
		 			</el-table-column> -->
				<!-- 		<el-table-column align="center" label="入库扫码时间">
		 				<template v-slot="{row}">{{row.warehousing_time?formatDate(row.warehousing_time,'yyyy-MM-dd hh:mm'):''}}</template>
		 			</el-table-column>
		 
		 			<el-table-column align="center" label="出库解绑时间">
		 				<template v-slot="{row}">{{row.Outbound_time?formatDate(row.Outbound_time,'yyyy-MM-dd hh:mm'):''}}</template>
		 			</el-table-column> -->
				<!-- 	<el-table-column align="center" label="操作">
		 				<template v-slot="{row}">
		 					<el-button type="text" @click="downXml(row.corpOrderID)" v-if="row.process == 2">XML下载</el-button>
		 					<el-button type="text" @click="gdhf(row)" v-if="row.process == 1">工单恢复</el-button>
		 					<span @click="del_gd(row)" style="color: red;margin-left: 20px;cursor: pointer;">删除</span>
		 				</template>
		 			</el-table-column> -->
				<!--  <el-table-column align="center" label="状 态" width="120">
		                 <template v-slot="{row}">
		                     <span :class="row.enable ? 'success' : 'error'" class="dot"/>
		                     <span>{{ row.enable ? '启用' : '禁用' }}</span>
		                 </template>
		             </el-table-column> -->
			</template>

			<el-dialog title="输入工单号" :visible.sync="dialogFormVisible" :modal="0==1" class="small_dia">
				<div style="margin: 20px 0 0 20px;">
					<span>工单号</span>
					<el-input style="width: 300px;margin-left: 10px;" v-model="gd_text" autocomplete="off"></el-input>
				</div>
				<!-- 		  <el-form :model="form">
		 				    <el-form-item label="托盘码" :label-width="formLabelWidth">
		 				      <el-input v-model="form.name" autocomplete="off"></el-input>
		 				    </el-form-item>
		 				    
		 				  </el-form> -->
				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取 消</el-button>
					<el-button type="primary" @click="add">确 定</el-button>
				</div>
			</el-dialog>
			<edit-dialog ref="child" v-model="editDialog" :data="row" :type="type" :time="time" @success="success" />
		</list-page>

	</div>
</template>

<script>
	import tableMixin from '@/mixin/tablePageMixin'
	import ListPage from '@/view/_common/ListPage'
	import EditDialog from './EditDialog'
	import RegionSelector from "@/component/RegionSelector"
	import {
		add,
		update,
		del,
		search,
		getLimitRegion
	} from "@/api/erp/index"

	import {
		isEmpty
	} from '@/util'
	import {
		wic
	} from "@/util/auth"
	import {
		elConfirm,
		elError,
		elSuccess
	} from "@/util/message"
	import SocketIO from 'socket.io-client'
	var request_url = localStorage.getItem('request_url')||''

	//    const socket  = SocketIO('ws://192.168.33.22:19103/mini-wms/wms')

	// console.log(socket,'socketsocketsocket')


	export default {
		name: "customerManagement",

		mixins: [tableMixin],

		components: {
			ListPage,
			EditDialog,
			RegionSelector
		},

		data() {
			return {
				gd_text: '',
				dialogFormVisible: false,
				paramA: "aa",
				paramB: 123,
				food: "",
				drink: "",
				code_: '', //箱子追溯码
				num: 2, // 两碗饭
				searchForm: {
					status: 1,
					name: '',
					address: '',
					linkman: '',
					linkphone: '',
					region: null,
					enable: null,
					text: ''
				},
				temp: {
					regionName: null,
					ctime: []
				},
				time: '',
				editDialog: false
			}
		},

		watch: {
			editDialog(val) {
				if (!val) {
					this.getList()
				}
			}
		},

		computed: {
			...wic({
				add,
				update,
				del
			}),

			listPageConfig() {
				return {
					pageLoading: this.config.operating,
					buttons: [
						// this.canAdd && {
						// 	icon: 'el-icon-plus',
						// 	e: this.addData,
						// 	content: '创建出库任务'
						// },
						// {
						// 	icon: 'el-icon-view',
						// 	e: this.see,
						// 	content: '查 看'
						// },
						// this.canUpdate && {icon: 'el-icon-edit', e: this.edit, content: '创建出库任务'},
						// this.canDel && {icon: 'el-icon-delete', e: this.del, content: '删 除'}
					],
					dataLoading: this.config.loading,
					search: {
						props: {
							model: this.searchForm
						},
						on: {
							search: this.search
						}
					},
					table: {
						props: {
							data: this.tableData
						},
						on: {
							'row-click': this.rowClick
						}
					},
					pagination: {
						props: {
							model: this.searchForm
						},
						on: {
							'current-change': this.pageChange
						}
					}
				}
			}
		},
		mounted() {
			// this.initWebSocket()
			// console.log(this.$socket, 'this.$socket')


		},

		created() {
			// let json = {
			// 	'action': 'listOrderIn',
			// 	'requestID': Date.parse(new Date()),
			// }
			// let a = JSON.stringify(json)
			// this.$socket.send(a)
			// this.getList()
		},

		methods: {
		
			getPallet() {
				if (!this.code_) {
						// this.$emit('elError', response.body.msg)
						this.$message({
							message: '请输入要查询的追溯码',
							type: 'warning'
						});
						return
					}
				this.$http.get(`/mini-wms/wms/query/pallet/box/${this.code_}`).then(response => {
					console.log(response.body.dataObj)
					if(response.body.code == '100000'){
						this.$message({
							message: response.body.msg,
							type: 'warning'
						});
						return
					}
					this.tableData = []
					this.tableData.push(response.body.dataObj)
				}).then((res)=>{
					console.log(111222)
					// this.$message({
					// 	message: '请求出错',
					// 	type: 'warning'
					// });
				})

			},

			del_gd(e) { //删除工单
				this.row = e
				console.log(this.row, 'this.row')
				elConfirm(`确定工单号【${this.row.corpOrderID}】的数据？`)
					.then(() => {
						// this.config.operating = true
						return this.$http.delete(`${request_url}/mini-wms/wms/out/orderout/${e.orderOutId}`).then(
							response => {
								this.getList()

							})

					})
					.then(() => this.success('删除成功'))
					.finally(() => this.config.operating = false)
			},
			downL(str, name) {
				let url =
					"https://dp-data.obs.cn-south-1.myhuaweicloud.com:443/files%2F5d6a8d5f8a4b4c618b83eac1baf95adf.jpg"
				// window.open(url);
				// var fs = require('fs');

				// 要保存的字符串, 需要先将数据转成字符串
				const stringData = str
				// dada 表示要转换的字符串数据，type 表示要转换的数据格式

				// stringData = this.showXml(stringData)
				const blob = new Blob([stringData], {
					type: 'application/json'
				})
				// 根据 blob生成 url链接
				const objectURL = URL.createObjectURL(blob)

				// 创建一个 a 标签Tag
				const aTag = document.createElement('a')
				// 设置文件的下载地址
				aTag.href = objectURL
				// 设置保存后的文件名称
				aTag.download = `${name}`;
				// 给 a 标签添加点击事件
				aTag.click()
				// 释放一个之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。
				// 当你结束使用某个 URL 对象之后，应该通过调用这个方法来让浏览器知道不用在内存中继续保留对这个文件的引用了。
				URL.revokeObjectURL(objectURL)

				// fs.writeFile('vue.txt', '写入文件内容', function (err) {
				// if (err) throw err;
				// 	console.log('文件已创建！');
				// });
				// let a = document.createElement("a");
				//      a.href = "C:/Users/admin/Desktop/cns.docx";
				//      a.download = 'cns.docx';
				//      a.click();

				// window.location.href = url
			},
			downXml(corpOrderId) {
				this.$http.get(`${request_url}/mini-wms/wms/out/orderout/detail/xml/${corpOrderId}`).then(response => {
					console.log(response.body.dataObj)
					this.downL(response.body.dataObj, response.body.data)
					// this.tableData = response.body.dataObj
				})
			},
			getList() {
				// this.$http
				this.$http.get('/mini-wms/wms/out/orderout/all').then(response => {
					console.log(response.body.dataObj)
					this.tableData = response.body.dataObj
				})
				// this.$ajaxGET({
				//   url: 'http://192.168.33.22:19103/mini-wms/wms/in/orderin/all'
				// }).then(response => {
				//   console.log(response.data);
				// }).catch(error => {
				//   console.error(error);
				// })
			},
			addpage() {
				if (!this.gd_text) {
					this.$http.post('/mini-wms/wms/out/orderout').then(response => {
						this.id = response.body.dataObj
						localStorage.setItem('gd_id', this.id)
						this.$refs.child.getDeatil();
						// console.log(response.body.dataObj)
						// this.tableData = response.body.dataObj
					})
				}
				if (this.gd_text) {
					this.$http.post(`${request_url}/mini-wms/wms/out/orderout?corpOrderId=${this.gd_text}`).then(
						response => {
							this.id = response.body.dataObj
							localStorage.setItem('gd_id', this.id)
							this.$refs.child.getDeatil();
							// console.log(response.body.dataObj)
							// this.tableData = response.body.dataObj
						})
				}

			},
			formatDate(date, fmt) {
				console.log(date, 'date')
				date = new Date(date)
				console.log(date, '78779998')

				if (/(y+)/.test(fmt)) {
					fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
				}
				let o = {
					'M+': date.getMonth() + 1,
					'd+': date.getDate(),
					'h+': date.getHours(),
					'm+': date.getMinutes(),
					's+': date.getSeconds()
				}
				for (let k in o) {
					if (new RegExp(`(${k})`).test(fmt)) {
						let str = o[k] + ''
						fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : this.padLeftZero(str))
					}
				}
				return fmt
			},
			padLeftZero(str) {
				return ('00' + str).substr(str.length)
			},
			setTime(date) {
				return formatDate(date, 'yyyy-MM-dd hh:mm')
			},
			getLimitRegion() {
				return getLimitRegion.request().then(data => data.data)
			},

			clearSidSearch() {
				this.searchForm.region = null
				this.temp.regionName = null
			},

			selectRegion(obj, ids) {
				this.searchForm.region = ids.join(',')
				this.temp.regionName = obj.fullname
			},

			mergeSearchForm() {
				return {
					...this.searchForm,
					startTime: this.temp.ctime ? this.temp.ctime[0] : null,
					endTime: this.temp.ctime ? this.temp.ctime[1] + 86400000 : null
				}
			},

			search() {
				// if (this.config.loading) return
				// this.config.loading = true
				// this.row = null
				// this.type = 'see'
				// search
				// 	.request(this.mergeSearchForm())
				// 	.then(({
				// 		data: {
				// 			list,
				// 			total
				// 		}
				// 	}) => {
				// 		this.searchForm.total = total
				// 		this.tableData = list
				// 	})
				// 	.finally(() => this.config.loading = false)
			},

			gdhf(row) {
				console.log(row, 'rowrow')
				this.$refs.audio.play();
				this.row = null
				this.type = 'add'
				this.time = Date.parse(new Date()) + ''
				this.editDialog = true
				localStorage.setItem('gd_id', row.corpOrderID)
				this.$refs.child.getDeatil();
			},

			addData() {
				this.dialogFormVisible = true
			},

			add() {
				elConfirm(`确定创建入库任务？`)
					.then(() => {
						this.row = null
						this.type = 'add'
						this.time = Date.parse(new Date()) + ''
						this.editDialog = true

						this.addpage()

						// this.$socket.send('some data1')
					})
			},

			see() {
				this.time = this.row.work_order_number
				if (isEmpty(this.row)) return elError('请选择要查看的工单')
				this.type = 'see'
				this.editDialog = true
			},

			edit() {

				if (isEmpty(this.row)) return elError('请选择要出库的工单')
				this.row.arr = [{
						case: 1,
						value: '41251151,4124141'
					},
					{
						case: 2,
						value: '421412,4141224141'
					}
				]
				this.type = 'edit'
				this.time = this.row.work_order_number
				this.editDialog = true
			},

			del() {
				if (isEmpty(this.row)) return elError('请选择要删除的客户')
				if (this.row.enable) return elError('已启用的客户不能删除')
				if (this.config.operating) return
				elConfirm(`确定删除客户【${this.row.name}】？`)
					.then(() => {
						this.config.operating = true
						return del.request({
							id: this.row.id,
							name: this.row.name
						})
					})
					.then(() => this.success('删除成功'))
					.finally(() => this.config.operating = false)
			},

			success(msg) {
				elSuccess(msg)
				this.editDialog = false
				this.search()
			}
		}
	}
</script>